package com.antis.olsl.library.widget;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.antis.olsl.library.R;

public class MyInputSearchLayout extends RelativeLayout {
    public MyInputSearchLayout(Context context) {
        super(context);
    }

    public MyInputSearchLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    EditText etSearch;
    ImageView imgClear;
    TextChangedListener listener;

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        etSearch = findViewById(R.id.et_search);
        imgClear = findViewById(R.id.img_clear);
        imgClear.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                etSearch.setText("");
            }
        });
        changeUi();
    }

    private void  changeUi(){
        imgClear.setVisibility(TextUtils.isEmpty(etSearch.getText().toString()) ? GONE :VISIBLE);
    }

    public void setHintText(String text){
        etSearch.setHint(text);
    }

    public void setListener(final TextChangedListener listener) {
        this.listener = listener;
        if(listener != null){
            etSearch.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    changeUi();
                    listener.onTextChangeListener(etSearch.getText().toString());
                }
            });
        }

    }

    public interface TextChangedListener{
        void onTextChangeListener(String text);
    }
}
